<template>
  <div class="app-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">应用管理</h1>
      <p class="page-description">管理您的AI应用配置</p>
    </div>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="openCreateDialog" class="create-btn">
        <el-icon><Plus /></el-icon>
        创建应用
      </el-button>
    </div>

    <!-- 应用列表表格 -->
    <div class="app-table-container">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无应用数据"
      >
        <el-table-column prop="Name" label="应用" width="220">
          <template #default="{ row }">
            <div class="app-name-cell">
              <el-avatar :size="32" :src="row.Avatar" class="app-avatar">
                {{ row.Name.charAt(0) }}
              </el-avatar>
              <div class="app-info">
                <span class="app-name">{{ row.Name }}</span>
                <span class="app-id">ID: {{ row.AppBizId }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="AppTypeDesc" label="应用类型" width="150">
          <template #default="{ row }">
            <el-tag type="info">
              {{ row.AppTypeDesc }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="AppStatusDesc" label="状态" width="200">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.AppStatus)">
              {{ row.AppStatusDesc }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="ModelAliasName" label="模型" width="180" />

        <el-table-column
          prop="UpdateTime"
          label="修改时间"
          width="180"
          sortable
        >
          <template #default="{ row }">
            {{ formatDate(row.UpdateTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="viewApp(row)"
                class="view-btn"
              >
                查看
              </el-button>
              <el-button
                size="small"
                :type="row.AppStatus === 2 ? 'success' : 'danger'"
                @click="toggleAppStatus(row)"
                :disabled="row.AppStatus != 2"
                class="status-btn"
              >
                {{ row.AppStatus === 2 ? "调用" : "调用" }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteAppFun(row)"
                class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建应用对话框 -->
    <el-dialog v-model="dialogVisible" title="创建应用" width="500px" draggable>
      <el-form
        :model="appForm"
        label-width="100px"
        :rules="rules"
        ref="appFormRef"
      >
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="appForm.name" placeholder="请输入应用名称" />
        </el-form-item>

        <el-form-item label="应用头像" prop="avatar">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-upload"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
            >
              <img v-if="appForm.avatar" :src="appForm.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="appForm.avatar"
              placeholder="或输入头像URL"
              class="avatar-url-input"
            />
          </div>
        </el-form-item>

        <el-form-item label="应用类型" prop="type">
          <el-select v-model="appForm.type" disabled>
            <el-option :value="'knowledge_qa'" :label="'知识问答管理'" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAppForm">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="callDialogVisible"
      title="调用信息"
      width="600px"
      draggable
    >
      <div class="call-info-container">
        <!-- 功能体验链接 -->
        <div class="function-section">
          <h3>功能体验链接</h3>
          <div class="experience-link">
            <el-input
              v-model="experienceLink"
              readonly
              placeholder="体验链接生成中..."
            >
              <template #append>
                <el-button @click="copyToClipboard(experienceLink)">
                  <el-icon><DocumentCopy /></el-icon>
                </el-button>
              </template>
            </el-input>
            <div class="button-group">
              <el-button style="width: 200px;" type="primary" @click="openExperienceLink">
                <el-icon><Promotion /></el-icon>
                立即体验
              </el-button>
              <!-- <el-button @click="regenerateLink">
                <el-icon><Refresh /></el-icon>
                重新生成
              </el-button>
              <el-button @click="shareLink">
                <el-icon><Share /></el-icon>
                分享链接
              </el-button>
              <el-button @click="showQRCode">
                <el-icon><Picture /></el-icon>
                分享二维码
              </el-button> -->
            </div>
          </div>
        </div>

        <!-- API管理 -->
        <div class="function-section">
          <h3>API管理</h3>
          <div class="api-info">
            <div class="api-item">
              <span class="label">AppKey:</span>
              <el-input v-model="apiInfo.appKey" readonly class="api-value">
                <template #append>
                  <el-button @click="copyToClipboard(apiInfo.appKey)">
                    <el-icon><DocumentCopy /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
            <div class="api-item">
              <span class="label">创建时间:</span>
              <el-input
                v-model="apiInfo.createTime"
                readonly
                class="api-value"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 二维码弹窗 -->
      <el-dialog
        v-model="qrCodeVisible"
        title="分享二维码"
        width="300px"
        append-to-body
      >
        <div class="qr-code-container">
          <div id="qr-code" ref="qrCodeRef"></div>
          <p class="qr-tip">扫描二维码体验应用</p>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { createApp, getApp, deleteApp,describeApp,getAppShareURL } from "@/api/modules/auth";
import { useRouter } from 'vue-router'
// import QRCode from 'qrcodejs2'

// 状态管理
const loading = ref(false);
const dialogVisible = ref(false);
const appFormRef = ref(null);
const router = useRouter()

// 分页相关
const currentPage = ref(1);
const pageSize = ref(6);
const total = ref(0);

// 表单数据
const appForm = ref({
  name: "",
  avatar:
    "",
  type: "knowledge_qa",
});

// 表格数据
const tableData = ref([]);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入应用名称", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
  ],
};

// 新增状态
const callDialogVisible = ref(false);
const qrCodeVisible = ref(false);
const experienceLink = ref("");
const apiInfo = ref({
  appKey: "",
  createTime: "",
});
const qrCodeRef = ref(null);
let qrCode = null;

// 方法
const formatDate = (timestamp) => {
  const date = new Date(timestamp * 1000);
  return date.toLocaleString();
};

const getStatusTagType = (status) => {
  switch (status) {
    case 1:
      return "info"; // 未上线
    case 2:
      return "success"; // 运行中
    default:
      return "info";
  }
};

const openCreateDialog = () => {
  appForm.value = {
    name: "",
    avatar:
      "",
    type: "knowledge_qa",
  };
  dialogVisible.value = true;
};

const viewApp = (app) => {
  // 这里应该跳转到应用详情页
  // ElMessage.info(`查看应用: ${app.Name}`);
  router.push({
    path:`/app/${app.AppBizId}/config`
  })
};
const dyApp = ref(null);
// 新增方法
const showCallDialog = async (app) => {
  dyApp.value = app;
  const res = await describeApp(app.AppBizId);
  // await getAppShareURL(app.AppBizId)
  if(res.status == 200){
    const data = res.data;
    if(data.AppStatus == 2){
      // 这里应该调用API获取应用调用信息
      experienceLink.value = 'http://localhost:9091/#/chat?AppBizId='+app.AppBizId
      callDialogVisible.value = true;

      // 模拟API返回的数据
      apiInfo.value = {
        appKey: data.AppKey,
        createTime: formatDate(app.UpdateTime),
      };
    }
  }else{
    ElMessage.error("应用key读取失败")
  }
};

const copyToClipboard = (text) => {
  navigator.clipboard
    .writeText(text)
    .then(() => ElMessage.success("复制成功"))
    .catch(() => ElMessage.error("复制失败"));
};

const openExperienceLink = () => {
  window.open(experienceLink.value, "_blank");
};

const regenerateLink = () => {
  // 这里应该调用API重新生成链接
  ElMessage.success("链接已重新生成");
};

const shareLink = () => {
  // 这里实现分享链接逻辑
  ElMessage.info("分享链接功能");
};

const showQRCode = () => {
  qrCodeVisible.value = true;
  nextTick(() => {
    if (qrCode) {
      qrCode.clear();
      qrCode.makeCode(experienceLink.value);
    } else {
      // qrCode = new QRCode(qrCodeRef.value, {
      //   text: experienceLink.value,
      //   width: 200,
      //   height: 200,
      //   colorDark: '#000000',
      //   colorLight: '#ffffff',
      //   correctLevel: QRCode.CorrectLevel.H
      // })
    }
  });
};

// 修改toggleAppStatus方法
const toggleAppStatus = (app) => {
  showCallDialog(app);
};

const deleteAppFun = (app) => {
  ElMessageBox.confirm(`确定要删除应用 "${app.Name}" 吗?`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const loading = ElLoading.service({
        lock: true,
        text: "请求中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const res = await deleteApp(app.AppBizId);
      // 这里应该调用API删除应用
      if (res.status == 200) {
        ElMessage.success("应用删除成功");
        fetchAppData(); // 刷新数据
      } else {
        ElMessage.error("应用删除失败");
      }
      loading.close();
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const submitAppForm = () => {
  appFormRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: "请求中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      try {
        const res = await createApp(
          appForm.value.name,
          appForm.value.avatar,
          appForm.value.type
        );
        if (res.status == 200) {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          fetchAppData(); // 刷新数据
        }
      } finally {
        loading.close();
      }
    }
  });
};

// 头像上传处理
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error("只能上传JPG/PNG格式的图片!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2MB!");
    return false;
  }
  return true;
};

const handleAvatarUpload = async (options) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "上传中...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    // 模拟上传过程
    await new Promise((resolve) => setTimeout(resolve, 1500));
    const mockUrl = ``;
    appForm.value.avatar = mockUrl;
    ElMessage.success("上传成功");
  } catch (error) {
    ElMessage.error("上传失败");
  } finally {
    loadingInstance.close();
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchAppData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchAppData();
};

// 获取应用数据
const fetchAppData = async () => {
  loading.value = true;
  try {
    const res = await getApp(currentPage.value);
    if (res.status === 200) {
      tableData.value = res.data.List;
      total.value = parseInt(res.data.Total);
    }
  } catch (error) {
    console.error("获取应用数据失败:", error);
    ElMessage.error("获取应用数据失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchAppData();
});
</script>

<style lang="scss" scoped>
.app-management-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }

  .page-description {
    font-size: 14px;
    color: #909399;
    margin: 0;
  }
}

.operation-area {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.create-btn {
  margin-right: 12px;
}

.app-table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;

  .app-name-cell {
    display: flex;
    align-items: center;

    .app-avatar {
      margin-right: 12px;
      background-color: #409eff;
      color: #fff;
      font-weight: bold;
    }

    .app-info {
      display: flex;
      flex-direction: column;

      .app-name {
        font-weight: 500;
        margin-bottom: 4px;
      }

      .app-id {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;

    .view-btn {
      background-color: #409eff;
      border-color: #409eff;
      color: white;
    }

    .status-btn {
      padding: 7px 12px;
    }

    .delete-btn {
      background-color: #f56c6c;
      border-color: #f56c6c;
      color: white;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 头像上传样式 */
.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
  margin-right: 12px;
}

.avatar-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
}

.avatar-url-input {
  flex: 1;
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f8fafc;

  :deep(.el-table__header th) {
    font-weight: 600;
    color: #303133;
  }
}
.call-info-container {
  // padding: 0 10px;

  .function-section {
    margin-bottom: 24px;

    h3 {
      font-size: 16px;
      color: #303133;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;
    }

    .experience-link {
      .button-group {
        margin-top: 12px;
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .el-button {
          flex: 1;
          min-width: 120px;
        }
      }
    }

    .api-info {
      .api-item {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        .label {
          width: 80px;
          font-size: 14px;
          color: #606266;
        }

        .api-value {
          flex: 1;
        }
      }
    }
  }
}

.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;

  #qr-code {
    margin: 10px 0;
  }

  .qr-tip {
    font-size: 14px;
    color: #909399;
    margin-top: 10px;
  }
}
</style>